import ToastComponent from '../../components/weui/toast'
// import { mergeOptions } from '../../libs/plugin_helper'

let $vm
// let watcher

const plugin = {
  install (vue, options = {}) {
    const Toast = vue.extend(ToastComponent)

    if (!$vm) {
      $vm = new Toast({
        el: document.createElement('div')
      })
      document.body.appendChild($vm.$el)
    }

    const defaults = {}
    for (let i in $vm.$options.props) {
      if (i !== 'value') {
        defaults[i] = $vm.$options.props[i].default
      }
    }
    Object.assign(defaults, options)
    mergeOptions($vm, options)

    const toast = {
      show (options = {}) {
        // reset first
        mergeOptions($vm, defaults)
        if (typeof options === 'string') {
          $vm.text = options
        } else if (typeof options === 'object') {
          mergeOptions($vm, options)
        }
        $vm.show = true
      },
      ok (text) {
        this.show({ text, type: 'success' })
      },
      loading (toggle = true) {
        toggle && this.show({
          type: 'loading',
          text: typeof toggle === 'string' ? toggle : '加载中',
          time: 0,
          isShowMask: true
        })
        !toggle && this.hide()
      },
      hide () {
        $vm.show = false
      }
    }

    if (!vue.$weui) {
      vue.$weui = {
        toast
      }
    } else {
      vue.$weui.toast = toast
    }

    window.alert = function (text) {
      toast.show({
        text,
        type: 'text',
        width: 'auto'
      })
    }

    vue.mixin({
      created: function () {
        this.$weui = vue.$weui
      }
    })
  }
}

const mergeOptions = function ($vm, options) {
  const _options = Object.assign({}, options)
  for (let i in _options) {
    $vm[i] = _options[i]
  }
}

export default plugin
export const install = plugin.install
